package holdem.network;

//~--- imports: JDK -----------------------------------------------------------

import java.io.IOException;

import java.net.ServerSocket;
import java.net.Socket;

import java.util.ArrayList;
import java.util.List;

public class Server {
    public static List<ClientHandler> users = new ArrayList<ClientHandler>();
    private static ServerSocket       serverSocket;
    public static String str;
    public static PokerDealer dealer;
    // print diagnosis messages to System.out if is true
    public static boolean debugMode = true;

    //~--- methods ------------------------------------------------------------

    private static void startServer() throws IOException
    {
	dealer = new PokerDealer();
	int intPort = 3333;

	serverSocket = new ServerSocket(intPort);
	System.out.println("Listen on port: " + intPort);
        int player = 0;

	while (true) 
        {
	    Socket clientSocket = serverSocket.accept();

	    System.out.println(clientSocket.getInetAddress().getHostName()
			       +" connected");

	    ClientHandler handler = new ClientHandler(clientSocket, player++);

	    users.add(handler);
	    new Thread(handler).start();
	}
    }

    public static synchronized void broadcastFromServer(NetworkEvent event)
    {
	for (int i = 0; i < users.size(); i++) {
	    try
            {
		if(!users.get(i).player.hasQuit)
                    users.get(i).sendMessage(event);
	    } catch (IOException ex)
            {
		System.err.println("Unable to send message");
	    }

	}
    }

    public static void main(String[] args) throws IOException
    {
	startServer();
    }
}
